<?php

class ApiAccessFilter extends CFilter
{

	/**
	 * @param CFilterChain $filterChain the filter chain that the filter is on.
	 * @return boolean
	 * @throw CHttpException
	 */
	public function preFilter($filterChain)
	{
		$controller = $filterChain->controller; /* @var $controller ApiController */
		if (isset($_POST['access_token'])) {
			$project = $controller->projectName;
			$route = $controller->route;
			$token = ApiToken::model()->findByToken($_POST['access_token']);
			if ($token !== null && ($route === 'api/logout' || $token->user->hasAccess($project, $route))) {
				$controller->token = $token;
				return true;
			}
		}
		throw new CHttpException(403, 'Permission denied');
	}
}
